<template>
  <view class="facilities-wrap">
    <view
      class="item"
      :class="type === '2' ? 'normal' : ''"
      v-for="item in faciliList"
      :key="item.id"
      @tap="onFacilityClick(item)"
    >
      <template v-if="item.facilitiesType === type">
        <image
          v-if="item.notOptionalIcon"
          class="icon"
          :src="onPitch(item.id) ? item.notOptionalIcon : item.optionalIcon"
        />
        <u-icon v-else name="photo" size="32"></u-icon>
        <text class="name" :class="onPitch(item.id) ? 'active' : ''">{{
          item.facilitiesName
        }}</text>
      </template>
    </view>
    <none-data v-if="faciliList.length === 0" />
  </view>
</template>
<script setup>
import { ref, watch } from "vue";
const emit = defineEmits(["handle-facilities"]);
const props = defineProps({
  list: {
    type: Array,
    default: [],
  },
  type: {
    type: String,
    default: "1", //1:基础设施 2：可选设施
  },
});
const faciliList = ref([]);
const currentList = ref([]);

watch(
  () => props.list,
  (value) => {
    if (value) {
      faciliList.value = value.filter((v) => v.facilitiesType === props.type);
    }
  },
  { immediate: true, deep: true }
);
watch(
  () => props.type,
  (value) => {
    faciliList.value = props.list.filter((v) => v.facilitiesType === value);
  },
  { immediate: true, deep: true }
);

const onFacilityClick = (facility) => {
  if (props.type === "2") {
    let indexToRemove = currentList.value.findIndex(
      (item) => item === facility.id
    );
    if (indexToRemove !== -1) {
      // 如果存在相同 value 的对象，则从数组中删除
      currentList.value.splice(indexToRemove, 1);
    } else {
      // 如果不存在相同 value 的对象，则添加到数组
      currentList.value.push(facility.id);
    }
    emit("handle-facilities", currentList.value);
  }
};
const onPitch = (facId) => {
  if (props.type !== "2") return;
  return currentList.value.indexOf(facId) !== -1;
};
</script>
<style lang="less" scoped>
.facilities-wrap {
  display: flex;
  flex-wrap: wrap;
  padding-left: 30rpx;
  .item {
    display: flex;
    align-items: center;
    height: 35rpx;
    margin: 10rpx 0;
    width: calc((100% - 20rpx) / 3);
    &.normal {
      .name {
        color: @color-light-grey-text;
      }
    }
    .name {
      font-family: "ali-m";
      color: @color-black-text;
      font-size: @font-size-23;
      margin-left: 13rpx;
      &.active {
        color: @color-black-text;
      }
    }
    .icon {
      width: 32rpx;
      height: 32rpx;
    }
  }
}
</style>
